<template>
	<view>
		<ksp-cropper mode="fixed" :width="selFileW" :height="selFileH" :url="fileUrl" @cancel="oncancel"
			@ok="onok"></ksp-cropper>
		<uni-card :isFull="true">
			<uni-forms ref="form" :rules="rules" :modelValue="form">
				<uni-forms-item label="名称" required name="name">
					<uni-easyinput placeholder="请输入商品名" v-model="form.name" />
				</uni-forms-item>
				<uni-forms-item label="价格" required name="price">
					<uni-easyinput placeholder="0.00" v-model="price" />
				</uni-forms-item>

				<uni-forms-item label="规格">
					<uni-easyinput placeholder="输入规格" v-model="form.specification" />
				</uni-forms-item>
				<uni-forms-item label="起售数量">
					<uni-easyinput placeholder="请输入起售数量" v-model="form.minSaleNum" type="number" />
				</uni-forms-item>
				<uni-forms-item label="库存">
					<uni-easyinput placeholder="请输入库存" v-model="form.stock" type="number" />
				</uni-forms-item>
				<uni-forms-item label="划线价" name="topPrice">
					<uni-easyinput placeholder="请输入划线价" v-model="topPrice" />
				</uni-forms-item>
				<uni-forms-item label="权重">
					<uni-easyinput placeholder="请输入权重" v-model="form.weight" type="number" />
				</uni-forms-item>
				<uni-forms-item label="分类">
					<view class="cate-sel" @click="showCate">
						<view>{{ showCateName || "请选择分类" }}</view>
						<uni-icons type="bottom" size="20" color="#999999"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item>
					<uni-file-picker title="商品logo" limit="1" file-mediatype="image" mode="grid" @select="selectImage"
						:value="selImage" @delete="delImage"></uni-file-picker>
				</uni-forms-item>
				<uni-forms-item>
					<uni-file-picker title="视频" limit="9" file-mediatype="video" mode="grid"
						@select="detailSelectVideo" :value="detailSelVideo" @delete="detailDelVideo"></uni-file-picker>
				</uni-forms-item>
				<uni-forms-item>
					<uni-file-picker title="商品展示" limit="9" file-mediatype="image" mode="grid"
						@select="detailSelectImage" :value="detailSelImage" @delete="detailDelImage"></uni-file-picker>
				</uni-forms-item>
				<uni-forms-item label="描述">
					<uni-easyinput type="textarea" placeholder="描述信息,最多2000字" v-model="form.description" />
				</uni-forms-item>
			</uni-forms>
		</uni-card>
		<view class="gaps-goods" :style="{height: 60 + wh + 'px'}">

		</view>

		<view class="bottom-fiex-area" :style="{paddingBottom: wh + 'px',height: 40 + wh + 'px'}">
			<!-- <button type="primary" @click="addGoodsForm">确认修改</button> -->
			<u-button type="success" text="确认修改" @click="addGoodsForm"></u-button>
		</view>

		<uni-popup ref="popup" type="bottom">
			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y">
				<uni-section title="请选择分类" type="line">
					<uni-list>
						<uni-list-item v-for="(cate, i) in cates" :key="cate.id" clickable @click="cateClick(cate)">
							<template v-slot:body>
								{{ cate.name }}
							</template>
						</uni-list-item>
					</uni-list>
				</uni-section>
			</scroll-view>
		</uni-popup>

	</view>
</template>

<script>
	import {
		getGoodsType,
	} from '@/api/shops/categoryManage/categoryManage.js'
	import {
		getGoods,
		editGoods
	} from '@/api/shops/goodsManage/goodsManage.js'
	import uploadFile from '@/utils/uploadFile.js'
	import {
		transform
	} from '@/minix/mixin.js'
	export default {
		mixins: [transform],
		data() {
			return {
				wh: 0,
				cates: {},
				showCateName: '',
				selImage: [],
				selVideo: [],
				detailSelImage: [],
				detailSelVideo: [],
				price: '',
				topPrice: '',
				fileUrl: '',
				selFileW: 1000,
				selFileH: 1000,

				eventChannel: {},

				form: {
					goodsType: '',
					name: '',
					description: '',
					multimediaUrl: [],
					detailUrl: [],
					videoUrl: [],
					specification: '',
					shopId: '',
					price: '',
					id: '',
					minSaleNum: 1,
					stock: 0,
					topPrice: null
				},
				rules: {
					// 对name字段进行必填验证
					name: {
						// name 字段的校验规则
						rules: [
							// 校验 name 不能为空
							{
								required: true,
								errorMessage: '请填写商品名',
							},
						],
					},
					price: {
						rules: [{
							required: true,
							errorMessage: '请填写价格',
						}, {
							format: 'number',
							errorMessage: '价格只能输入数字'
						}]
					}
				}
			}
		},
		onLoad: function(option) {
			const sysInfo = uni.getSystemInfoSync()
			this.wh = sysInfo.safeAreaInsets.bottom
			this.form.shopId = option.shopId
			this.form.id = option.goodsId
			this.eventChannel = this.getOpenerEventChannel();
			this.init()
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		watch: {
			price(val) {
				if (!val) {
					this.form.price = ''
					return
				}
				if (!isNaN(val)) {
					this.form.price = parseFloat(val * 100).toFixed(0)
				} else {
					this.form.price = val
				}
			},
			topPrice(val) {
				if (!val) {
					this.form.topPrice = ''
					return
				}
				if (!isNaN(val)) {
					this.form.topPrice = val * 100
				} else {
					this.form.topPrice = val
				}
			}
		},
		methods: {
			init() {
				getGoods(this.form.id).then((res) => {
					let logos = []
					if (res.multimediaUrl) {
						logos = res.multimediaUrl.split(",")
					}
					let details = []
					if (res.detailUrl) {
						details = (res.detailUrl || '').split(',')
					}
					let videos = []
					if(res.videoUrl) {
						videos = (res.videoUrl || '').split(',')
					}

					this.form = res
					this.form.multimediaUrl = []
					this.form.detailUrl = []
					this.form.videoUrl = []

					this.selImage = logos.map(item => {
						return {
							"name": item.slice(item.lastIndexOf('/') + 1),
							"extname": item.slice(item.lastIndexOf('.') + 1),
							"url": item,
							"up": false
						}
					})
					
					this.detailSelImage = details.map(item => {
						return {
							"name": item.slice(item.lastIndexOf('/') + 1),
							"extname": item.slice(item.lastIndexOf('.') + 1),
							"url": item,
							"up": false
						}
					})
					this.detailSelVideo = videos.map(item => {
						return {
							"name": item.slice(item.lastIndexOf('/') + 1),
							"extname": item.slice(item.lastIndexOf('.') + 1),
							"url": item,
							"up": false
						}
					})

					this.price = this.priceTransform(this.form.price, 2, '')
					this.topPrice = this.priceTransform(this.form.topPrice, 2, '')
					getGoodsType(this.form.shopId).then(res => {
						this.cates = res
						res.forEach((item) => {
							if (item.id === this.form.goodsType)
								this.showCateName = item.name
							return
						})
					})
				}).catch((e) => {

				})
			},

			showCate() {
				getGoodsType(this.form.shopId).then(res => {
					this.cates = res
					this.$refs.popup.open('bottom')
				})
			},
			cateClick(cate) {
				this.$refs.popup.close()
				this.form.goodsType = cate.id
				this.showCateName = cate.name
			},

			addGoodsForm(form) {
				let _this = this;
				this.$refs.form.validate().then(res => {
					uni.showModal({
						content: '确认保存吗?',
						success: (res) => {
							if (res.confirm) {
								uni.showLoading({
									title: '正在上传图片',
									mask: true
								})
								this.form.multimediaUrl = []
								this.form.detailUrl = []

								let logoPromise = this.selImage.map(item => {
									if (item.up) {
										return uploadFile(item.url,
											`shopgoods/${this.form.shopId}/logo/`).then(
											url => {
												_this.form.multimediaUrl.push(url.fileUrl)
											})
									} else {
										_this.form.multimediaUrl.push(item.url)
									}
								})

								logoPromise.push(...this.detailSelImage.map(item => {
									if (item.up) {
										return uploadFile(item.url,
												`shopgoods/${this.form.shopId}/detail/`)
											.then(url => {
												_this.form.detailUrl.push(url.fileUrl)
											})
									} else {
										_this.form.detailUrl.push(item.url)
									}
								}))
								logoPromise.push(...this.detailSelVideo.map(item => {
									if(item.up) {
										return uploadFile(item.url,
										`shopgoods/${this.form.shopId}/videos/`, false)
										.then(url => {
											_this.form.videoUrl.push(url.fileUrl)
										})
									} else {
										_this.form.videoUrl.push(item.url)
									}
								}))
								
								Promise.all(logoPromise).then(() => {
									uni.hideLoading()
									uni.showLoading({
										title: '正在保存商品',
										mask: true
									})
									this.form.multimediaUrl = this.form.multimediaUrl.join(",")
									this.form.detailUrl = this.form.detailUrl.join(',')
									this.form.videoUrl = this.form.videoUrl.join(',')
									editGoods(this.form).then(res => {
										_this.eventChannel.emit('goodsListChange', {
											data: true
										})
										uni.showToast({
											title: '保存成功'
										})
										uni.navigateBack()
									}).finally(() => {
										uni.hideLoading()
									})
								})
							}
						}
					})

				}).catch(() => {

				})
			},
			oncancel() {
				this.fileUrl = ''
			},
			selectImage(e) {
				this.fileUrl = e.tempFilePaths[0]
			},
			onok(ev) {
				this.fileUrl = '',
				this.selImage.push({
					name : new Date().getTime(),
					extname: 'png',
					url:ev.path,
					'up':true
				})
			},
			delImage(res) {
				this.selImage = []
			},
			detailSelectImage(e) {
				this.detailSelImage.push(...e.tempFiles.map(({
					name,
					extname,
					url
				}) => ({
					name,
					extname,
					url,
					up: true
				})));
			},
			detailSelectVideo(e) {
				this.detailSelVideo.push(...e.tempFiles.map(({
					name,
					extname,
					url
				}) => ({
					name,
					extname,
					url,
					up: true
				})));
			},
			detailDelImage(e) {
				this.detailSelImage = this.detailSelImage.filter(item => {
					return item.name !== e.tempFile.name
				})
			},
			detailDelVedio(e) {
				this.detailSelVideo = this.detailSelVideo.filter(item => {
					return item.name !== e.tempFile.name
				})
			}
		}
	}
</script>

<style lang="scss">
	.bottom-fiex-area {
		background-color: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		display: flex;
		justify-content: center;
		align-items: center;
		border-top: 1px solid #bcbcbc;
		z-index: 2;

	}

	.cate-sel {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: flex-end;
		font-size: 13px;
		color: #999999;
	}

	.gaps-goods {
		height: 60px;
	}

	.scroll-Y {
		height: 500rpx;
		white-space: nowrap;
		width: 100%;
		background-color: #fff;
	}
</style>